package com.component;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.faces.context.FacesContext;

import org.operamasks.faces.annotation.Action;
import org.operamasks.faces.annotation.BeforeRender;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.Inject;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.component.tree.base.TreeDataProvider;
import org.operamasks.faces.component.tree.impl.UITree;
import org.operamasks.faces.component.tree.impl.UITreeNode;
import org.operamasks.faces.component.widget.UIButton;
import org.operamasks.faces.event.ajax.TreeNodeEvent;
import org.operamasks.faces.user.ajax.PartialUpdateManager;

import com.base.commons.SpringBeanHolder;
import com.base.organization.entity.CentralUnit;
import com.base.organization.entity.DepartmentalUnit;
import com.base.organization.entity.Employee;
import com.base.organization.entity.Employee.SEX;
import com.base.organization.service.IOrganizationService;
import com.base.security.SecurityConst;
import com.base.security.entity.SecurityUser;
import com.base.utils.DataStructureUtils;

/**
 * 
 * This managed bean is generated automatically
 */
@ManagedBean(name = "component_personTreeBean", scope = ManagedBeanScope.SESSION)
public class PersonTreeBean implements Serializable {
	private IOrganizationService orgService = SpringBeanHolder
			.getBean("orgService");
	//private IUnitAndDepConfigDao configDao = SpringBeanHolder
			//.getBean("unitAndDepDAO");
	@Inject
	private FacesContext context;
	@Inject
	private PartialUpdateManager update;
	@Bind(id = "ps_txt", attribute = "value")
	private String ps_txt;
	@Bind(id = "selectedText", attribute = "value")
	private String selectedText;
	@Bind(id = "selectedId", attribute = "value")
	private String selectedId;
	// 搜索map
	private Map<String, Set<Integer>> searchMap;
	/**
	 * 传递的部门名称
	 */
	private String depId;

	private String departmentName;

	@Bind
	private UITree ps_selectTree;
	@Bind(id = "ps_selectTree")
	private TreeDataProvider treeData_ps_selectTree = new TreeDataProvider() {
		public Object[] getChildren(Object node) {
			// 搜索
			if (ps_txt != null && !"".equals(ps_txt)) {
				if (departmentName == null || "".equals(departmentName)) {
					if (node == null) {
						return new String[] { "机构" };
					}
					if ("机构".equals(node)) {
						Set<Integer> topUnits = searchMap
								.get(SecurityConst.MAP_KEY_ORG);
						return orgService.getTopCentralUnitByIds(
								DataStructureUtils.setToList(topUnits))
								.toArray();
					}
					if (node instanceof CentralUnit) {
						Set<Integer> topUnits = searchMap
								.get(SecurityConst.MAP_KEY_ORG);
						CentralUnit cu = (CentralUnit) node;
						List<CentralUnit> units = orgService
								.getDirectChildUnitsByIds(
										cu.getCentralUnitId(),
										DataStructureUtils.setToList(topUnits));
						// 出机构的部门与机构的下级机构
						List<DepartmentalUnit> deps = orgService
								.getTopDeptOfUnit(cu.getCentralUnitId());
						int depSize = deps.size();
						int unitSize = units.size();
						Object[] result = new Object[depSize + unitSize];
						// 出机构部门
						for (int i = 0; i < depSize; i++) {
							result[i] = deps.get(i);
						}
						// 出子机构
						for (int n = 0; n < unitSize; n++) {
							result[n + depSize] = units.get(n);
						}
						return result;
					}
					if (node instanceof DepartmentalUnit) {
						List<Integer> listDepts = DataStructureUtils
								.setToList(searchMap
										.get(SecurityConst.MAP_KEY_DEPT));
						List<Integer> userIds = DataStructureUtils
								.setToList(searchMap
										.get(SecurityConst.MAP_KEY_USER));
						DepartmentalUnit du = (DepartmentalUnit) node;
						List<DepartmentalUnit> temp = orgService
								.getDirectChildDeptsByIds(du
										.getDepartmentalUnitId(), listDepts);
						// 如果无子部门，出部门下面的员工
						if (temp.isEmpty()) {
							return orgService.getPersonsOfDeptByIds(
									du.getDepartmentalUnitId(), userIds)
									.toArray();
						}
						List<SecurityUser> users = orgService
								.getPersonsOfDeptByIds(du
										.getDepartmentalUnitId(), userIds);
						int userSize = users.size();
						int depSize = temp.size();
						Object[] result = new Object[depSize + userSize];
						// 如果该部门下面还有人，把人也需要出来。
						for (int i = 0; i < userSize; i++) {
							result[i] = users.get(i);
						}
						// 如果有子部门，出子部门
						for (int n = 0; n < depSize; n++) {
							result[n + userSize] = temp.get(n);
						}
						return result;
					}
					if (node instanceof SecurityUser)
						return null;
				} // else {
				// Browser.execClientScript("window.alert('不支持搜索');");
				// return null;
				// }
			} else {
				if (departmentName == null || "".equals(departmentName)) {
					// if (depId == null || "".equals(depId)) {
					if (node == null) {
						return new String[] { "机构" };
					}
					if ("机构".equals(node)) {
						return orgService.getTopCentralUnit().toArray();
					}
					if (node instanceof CentralUnit) {
						CentralUnit cu = (CentralUnit) node;
						List<CentralUnit> units = orgService
								.getDirectChildUnits(cu.getCentralUnitId());
						// 出机构的部门与机构的下级机构
						List<DepartmentalUnit> deps = orgService
								.getTopDeptOfUnit(cu.getCentralUnitId());
						int depSize = deps.size();
						int unitSize = units.size();
						Object[] result = new Object[depSize + unitSize];
						// 出机构部门
						for (int i = 0; i < depSize; i++) {
							result[i] = deps.get(i);
						}
						// 出子机构
						for (int n = 0; n < unitSize; n++) {
							result[n + depSize] = units.get(n);
						}
						return result;
					}
					if (node instanceof DepartmentalUnit) {
						DepartmentalUnit du = (DepartmentalUnit) node;
						List<DepartmentalUnit> temp = orgService
								.getDirectChildDepts(du.getDepartmentalUnitId());
						// 如果无子部门，出部门下面的员工
						if (temp.isEmpty()) {
							return orgService.getPersonsOfDept(
									du.getDepartmentalUnitId()).toArray();
						}
						List<SecurityUser> users = orgService
								.getPersonsOfDept(du.getDepartmentalUnitId());
						int userSize = users.size();
						int depSize = temp.size();
						Object[] result = new Object[depSize + userSize];
						// 如果该部门下面还有人，把人也需要出来。
						for (int i = 0; i < userSize; i++) {
							result[i] = users.get(i);
						}
						// 如果有子部门，出子部门
						for (int n = 0; n < depSize; n++) {
							result[n + userSize] = temp.get(n);
						}
						return result;
					}
					if (node instanceof SecurityUser)
						return null;
					// }
				} else {
					if (depId != null && !"".equals(depId)) {
						if (node == null) {
							return new String[] { "机构" };
						}
						if ("机构".equals(node)) {
							List<DepartmentalUnit> deps = new ArrayList<DepartmentalUnit>();
							DepartmentalUnit du = orgService
									.getDepartmentalUnitById(Integer
											.parseInt(depId));
							if (du != null)
								deps.add(du);
							return deps.toArray();
						}
						if (node instanceof DepartmentalUnit) {
							DepartmentalUnit du = (DepartmentalUnit) node;
							List<DepartmentalUnit> temp = orgService
									.getDirectChildDepts(du
											.getDepartmentalUnitId());
							// 如果无子部门，出部门下面的员工
							if (temp.isEmpty()) {
								return orgService.getPersonsOfDept(
										du.getDepartmentalUnitId()).toArray();
							}
							List<SecurityUser> users = orgService
									.getPersonsOfDept(du
											.getDepartmentalUnitId());
							int userSize = users.size();
							int depSize = temp.size();
							Object[] result = new Object[depSize + userSize];
							// 如果该部门下面还有人，把人也需要出来。
							for (int i = 0; i < userSize; i++) {
								result[i] = users.get(i);
							}
							// 如果有子部门，出子部门
							for (int n = 0; n < depSize; n++) {
								result[n + userSize] = temp.get(n);
							}
							return result;
						}
						if (node instanceof SecurityUser)
							return null;
					}
				}
			}
			return null;
		}

		public String getHref(Object nodeData) {
			return null;
		}

		public String getHrefTarget(Object nodeData) {
			return null;
		}

		public String getIcon(Object nodeData) {
			if (nodeData instanceof CentralUnit) {
				if (((CentralUnit) nodeData).getParentCentralUnitId() == null)
					return context.getExternalContext().getRequestContextPath()
							+ "/images/topOrg.gif";
				else
					return context.getExternalContext().getRequestContextPath()
							+ "/images/subOrg.gif";
			}
			if (nodeData instanceof DepartmentalUnit) {
				if (((DepartmentalUnit) nodeData).getParentDepartmentalUnitId() == null)
					return context.getExternalContext().getRequestContextPath()
							+ "/images/topDepart.gif";
				else
					return context.getExternalContext().getRequestContextPath()
							+ "/images/subDepart.gif";
			}
			if (nodeData instanceof SecurityUser) {
				SecurityUser su = (SecurityUser) nodeData;
				Set<Employee> es = su.getEmployee();
				Employee e = es == null ? null : es.isEmpty() ? null : es
						.iterator().next();
				if (e != null && e.getSex() != null
						&& SEX.WOMAN.equals(e.getSex()))
					return context.getExternalContext().getRequestContextPath()
							+ "/images/women.gif";
				else
					return context.getExternalContext().getRequestContextPath()
							+ "/images/man.gif";
			}
			return null;
		}

		public String getText(Object nodeData) {
			if (nodeData instanceof CentralUnit)
				return ((CentralUnit) nodeData).getName();
			if (nodeData instanceof DepartmentalUnit)
				return ((DepartmentalUnit) nodeData).getName();
			if (nodeData instanceof SecurityUser)
				return ((SecurityUser) nodeData).getFullname();
			if (nodeData != null)
				return nodeData.toString();
			return null;
		}

		public boolean isCascade(Object nodeData) {
			return false;
		}

		public Boolean isChecked(Object nodeData) {
			return null;
		}

		public boolean isExpanded(Object nodeData) {
			if (nodeData == null)
				return false;
			if (ps_txt != null && !"".equals(ps_txt))
				return true;
			if (nodeData instanceof DepartmentalUnit) {
				DepartmentalUnit du = (DepartmentalUnit) nodeData;
				List<DepartmentalUnit> temp = orgService.getDirectChildDepts(du
						.getDepartmentalUnitId());
				// 如果无子部门，出部门下面的员工
				if (temp.isEmpty()) {
					if (du.getPersons() == null || du.getPersons().isEmpty())
						return true;
				} else
					return false;
			}
			if (nodeData instanceof SecurityUser)
				return true;
			return false;
		}

		public boolean isLeaf(Object nodeData) {
			if (nodeData instanceof SecurityUser)
				return true;
			return false;
		}
	};

	@Action(id = "ps_selectTree", event = "onclick")
	public void click(TreeNodeEvent event) {
		UITreeNode node = event.getEventNode();
		Object data = node.getUserData();
		if (data == null)
			return;
		if (data instanceof SecurityUser) {
			SecurityUser su = (SecurityUser) data;
			selectedId = su.getUserId().toString();
			selectedText = su.getFullname();
			update.markAttributeUpdate("selectedId", "value");
			update.markAttributeUpdate("selectedText", "value");
		}
	}

	@Action(id = "userSearch")
	public void searchUser() {
		if (ps_txt != null && !"".equals(ps_txt)) {
			searchMap = orgService.getDepAndUserMap(ps_txt);
		}
		ps_selectTree.setRootVisible(false);
		ps_selectTree.setAutoScroll(true);
		ps_selectTree.repaint();
	}

	@Bind
	private UIButton userSearch;

	@BeforeRender
	public void beforeRender(boolean isPostback) {
		if (!isPostback) {
			departmentName = context.getExternalContext()
					.getRequestParameterMap().get("departmentName");
			/*if (departmentName != null && !"".equals(departmentName)) {
				List<UnitAndDepConfig> configList = configDao
						.findAllByNamedQuery(
								"unitAndDepConfig.getConfigByName",
								departmentName);
				if (configList != null && configList.size() > 0) {
					depId = configList.get(0).getDepOrUnitId();
					userSearch.setDisabled(true);
					userSearch.setTitle("不支持搜索");
				}
			}*/
			ps_txt = null;
			searchMap = null;
		}
	}
}
